<?php

declare(strict_types=1);
/**
 * This file is part of MoChat.
 * @link     https://mo.chat
 * @document https://mochat.wiki
 * @contact  group@mo.chat
 * @license  https://github.com/mochat-cloud/mochat/blob/master/LICENSE
 */
namespace MoChat\Plugin\ContactStage\Action\Dashboard;

use Hyperf\Di\Annotation\Inject;
use Hyperf\HttpServer\Annotation\Controller;
use Hyperf\HttpServer\Annotation\Middleware;
use Hyperf\HttpServer\Annotation\Middlewares;
use Hyperf\HttpServer\Annotation\RequestMapping;
use MoChat\App\Common\Middleware\DashboardAuthMiddleware;
use MoChat\App\Rbac\Middleware\PermissionMiddleware;
use MoChat\Framework\Action\AbstractAction;
use MoChat\Framework\Constants\ErrorCode;
use MoChat\Framework\Exception\CommonException;
use MoChat\Framework\Request\ValidateSceneTrait;
use MoChat\Plugin\ContactStage\Contract\ContactStageContract;
use MoChat\Plugin\ContactStage\Contract\ContactStageEmployeeContract;

/**
 * 客户阶段删除.
 *
 * Class Destroy.
 * @Controller
 */
class Destroy extends AbstractAction
{
    use ValidateSceneTrait;

    /**
     * @Inject
     * @var ContactStageContract
     */
    protected $contactStageService;

    /**
     * @Inject
     * @var ContactStageEmployeeContract
     */
    protected $contactStageEmployeeService;

    /**
     * @RequestMapping(path="/dashboard/contactStage/destroy", methods="DELETE")
     * @Middlewares({
     *     @Middleware(DashboardAuthMiddleware::class),
     *     @Middleware(PermissionMiddleware::class)
     * })
     * @return array 返回数组
     */
    public function handle(): array
    {
        // 验证接受参数
        $this->validated($this->request->all(), 'destroy');
        $id = (int) $this->request->input('stageId');

        if (! empty($this->contactStageEmployeeService->getContactStageEmployeeByStageId($id))) {
            throw new CommonException(ErrorCode::SERVER_ERROR, '请求失败，该阶段下有客户，请将客户转移到其他阶段后再删除');
        }
        // 删除
        $client = $this->container->get(ContactStageContract::class);
        $res = $client->deleteContactStage($id);

        if (! $res) {
            throw new CommonException(ErrorCode::SERVER_ERROR, '删除失败');
        }

        return [];
    }

    /**
     * 验证规则.
     *
     * @return array 响应数据
     */
    protected function rules(): array
    {
        return [
            'stageId' => 'required | integer | bail',
        ];
    }

    /**
     * 验证错误提示.
     * @return array 响应数据
     */
    protected function messages(): array
    {
        return [
            'stageId.required' => '阶段id 必填',
            'stageId.integer' => '阶段id 必须为整型',
        ];
    }
}
